package com.mach.platform.security;

import com.google.common.collect.Sets;
import com.mach.platform.domain.CustomizeUserInfo;
import com.mach.platform.domain.base.Account;
import com.mach.platform.domain.base.Permission;
import com.mach.platform.exception.AccountForbiddenException;
import com.mach.platform.repository.PermissionRepo;
import com.mach.platform.repository.RoleRepo;
import com.mach.platform.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Administrator
 * @Description: 安全框架--查询密码--放进角色权限等的信息
 * @Package: com.mach.platform.com.mach.platform.service
 * @Time create on 2017/11/22 14:23
 */
@Slf4j
@Primary
@Service
public class UserDetailServiceImpl implements UserDetailsService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PermissionRepo permissionRepo;

	@Autowired
	private RoleRepo roleRepo;

	@Override
	public UserDetails loadUserByUsername (String username) throws UsernameNotFoundException {

		Account user = userRepository.findByUsername(username);

		if (user != null) {

			if (!user.isEnabled()) {
				log.info("账号已被禁用，无法登陆，请联系管理员！");
				throw new AccountForbiddenException("账号已被禁用，无法登陆，请联系管理员！");
			}

			return new CustomizeUserInfo(user.getId(), user.getUsername(), user.getPassword(), user.getName(),
					user.getEmail(), user.getMobile(), obtainGrantedAuthorities(username));
		} else {
			throw new UsernameNotFoundException("用户名或密码不正确");
		}

	}

	/**
	 * 获得用户所有角色的权限集合
	 *
	 * @param username 用户名
	 * @return Set<GrantedAuthority>
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities (String username) {

		List<Permission> rolePerms = permissionRepo.loadPermissionsByUserName(username);
		List<Map> roles = roleRepo.loadUserRolesByUserName(username);

		Set<GrantedAuthority> authSet = Sets.newHashSet();

		for (Permission p : rolePerms) {
			authSet.add(new SimpleGrantedAuthority(p.getContent()));
		}

		if (roles.size() > 0) {
			roles.forEach(item->{
				authSet.add(new SimpleGrantedAuthority(item.get("content").toString()));
			});
		}

		return authSet;
	}

}
